/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package de.workingtimemanager.urb;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import de.workingtimemanager.urb.db.DatabaseHandler;
import de.workingtimemanager.urb.entities.Project;
import de.workingtimemanager.urb.entities.User;
import de.workingtimemanager.urb.entities.WorkDay;
import de.workingtimemanager.urb.excel.ExcelWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import jxl.write.WriteException;
import org.joda.time.DateTime;

/**
 *
 * @author CK05102
 */
public class ViewTimersActivity extends Activity {

    Context context;
    DatabaseHandler db;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        // ToDo add your GUI initialization code here  
        setContentView(R.layout.viewtimers);

        db = new DatabaseHandler();
        context = this;

        createView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        setContentView(R.layout.viewtimers);
        createView();
    }

    private void createView() {
        LinearLayout layout = (LinearLayout) findViewById(R.id.viewtimers_timerbuttons_layout);
        layout.removeAllViewsInLayout();

        try {
            db.open(this);
            WorkDay oldActive = db.getActiveUser().getActiveProject().getActiveWorkDay();
            if (oldActive != null) {
                oldActive.setActive(false);
            }

            User activeUser = db.getActiveUser();
            Project activeProject = activeUser.getActiveProject();

            TextView userView = (TextView) findViewById(R.id.viewtimers_activeuser_text);
            userView.setText(activeUser.getUSERNAME() + ":" + activeProject.getProjectName());

            for (int i = 1; i < activeProject.getDays().size(); i++) {
                final Button button = new Button(this);
                button.setText(activeProject.getDays().elementAt(i).getDATE());
//                button.setText(activeProject.getDays().elementAt(i).getDATE() + " " + activeProject.getDays().elementAt(i).getSTARTTIME());
                button.setOnClickListener(new OnClickListener() {

                    public void onClick(View v) {
                        try {
                            db.open(context);
                            Project activeProject = db.getActiveUser().getActiveProject();
                            WorkDay activeWorkDay = activeProject.getWorkDayByName(button.getText().toString());
                            activeWorkDay.setActive(true);
                            db.insert(activeWorkDay);
                        } finally {
                            db.close();
                        }
                        startActivity(new Intent(context, ExamineDayActivity.class));
                    }
                });
                button.setOnLongClickListener(new View.OnLongClickListener() {

                    public boolean onLongClick(View arg0) {
                        //create yes/no dialog
                        AlertDialog.Builder builder = new AlertDialog.Builder(context);
                        builder.setMessage("Are you sure you want to save the workingday in excelformat?").setCancelable(false).setPositiveButton("Yes", new DialogInterface.OnClickListener() {

                            public void onClick(DialogInterface dialog, int id) {
                                try {
                                    db.open(context);
                                    User activeUser = db.getActiveUser();
                                    ExcelWriter writer = new ExcelWriter(parseExcelPath(activeUser));
                                    writer.write(activeUser);
                                } catch (IOException ex) {
                                    Logger.getLogger(ViewTimersActivity.class.getName()).log(Level.SEVERE, null, ex);
                                } catch (WriteException ex) {
                                    Logger.getLogger(ViewTimersActivity.class.getName()).log(Level.SEVERE, null, ex);
                                } finally {
                                    db.close();
                                    dialog.cancel();
                                }
                            }
                        }).setNegativeButton("No", new DialogInterface.OnClickListener() {

                            public void onClick(DialogInterface dialog, int id) {
                                dialog.cancel();
                            }
                        });
                        AlertDialog alert = builder.create();
                        alert.show();
                        return true;
                    }
                });

                layout.addView(button);
            }

            final Button createButton = (Button) findViewById(R.id.viewtimers_createtimer_button);
            createButton.setOnClickListener(new OnClickListener() {

                public void onClick(View v) {
                    startActivity(new Intent(context, TimerActivity.class));
                }
            });
        } finally {
            db.close();
        }

    }

    private String parseDateTime(DateTime date) {
        StringBuilder stringBuffer = new StringBuilder();
        stringBuffer.append(date.getDayOfMonth());
        stringBuffer.append("-");
        stringBuffer.append(date.getMonthOfYear());
        stringBuffer.append("-");
        stringBuffer.append(date.getYear());
        return stringBuffer.toString();
    }

    private String parseExcelPath(User user) {
        StringBuilder stringBuffer = new StringBuilder();
        stringBuffer.append(context.getExternalFilesDir(null));
        stringBuffer.append("/");
        stringBuffer.append(user.getUSERNAME());
        stringBuffer.append(".xls");
        return stringBuffer.toString();
    }
}
